package cn.sfa.controller.manage;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.sfa.common.pagination.Pagination;
import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.FilterSpesChar;
import cn.sfa.common.utils.WebInitBinderContoller;
import cn.sfa.entity.affixItem.SaleAffixItem;
import cn.sfa.entity.news.SaleNews;
import cn.sfa.entity.users.Branch;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.affix.AffixService;
import cn.sfa.service.login.LoginService;
import cn.sfa.service.manage.NewsService;

/**
 * 
* 类名称：NewsController   
* 类描述： 公告管理处理类
* 创建人：LLY   
* 创建时间：2012-2-27  
* 修改人：LLY   
* 修改时间：2012-2-27   
* 修改备注：   
* @version
 */
@Controller
@RequestMapping("manage/news/index")
public class NewsController extends WebInitBinderContoller{

	Logger log = LoggerFactory.getLogger(NewsController.class);
	@Autowired
	LoginService loginService;
	@Autowired
	NewsService newsService;
	@Autowired
	AffixService affixService;
	private Pagination pagination;//分页
	
	public Pagination getPagination() {
		return pagination;
	}

	public void setPagination(Pagination pagination) {
		this.pagination = pagination;
	}
	
	/**
	 * 转到添加公告页面
	 * @param saleNews
	 * @return String
	 */
	@RequestMapping("/addnews")
	public String addNews(SaleNews saleNews,HttpServletRequest request)
	{
		request.getSession().removeAttribute("count");//清除附件个数
		request.getSession().setAttribute("iffixs", new ArrayList());//装载附件地址
		return "/manage/news/addnews";
	}
	
	
	@RequestMapping("/validate")
	public void validate(SaleNews saleNews,HttpServletRequest request,ModelMap map,
			HttpServletResponse response) throws Exception
	{
		int count=0;
		String json="";
		String newsTitle="";
		String newsContent="";
		
		String path = request.getContextPath();
		  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
		//表单验证
		if(CommonUtil.isEmpty(saleNews.getNewsTitle().trim()))
		{
			newsTitle="公告标题不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(saleNews.getNewsContent().trim()))
		{
			newsContent="公告内容不能为空！";
			count=count+1;
		}else if(saleNews.getNewsTitle().length()<6 || saleNews.getNewsTitle().length()>50)
		{
			newsTitle="公告标题长度必须在6到50位";
			count=count+1;

		}else if(saleNews.getNewsContent().length()>100000)
		{
			newsContent= "公告内容长度必须小于100000位";
			count=count+1;
		}else if(!FilterSpesChar.isTrueImage(saleNews.getNewsContent(),basePath))
		{
			newsContent="图片路径不正确，可能会导致图片不能正常显示！";
			count=count+1;
		}
		
		PrintWriter out=response.getWriter();
		boolean result=count==0;
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");

        
            JSONObject temp = new JSONObject();
            temp.put("result",result);
            temp.put("newsTitle", newsTitle);
            temp.put("newsContent",newsContent);
            
        
        out.print(temp.toString());
		out.flush();
		out.close();
	}
	/**
	 * 添加公告
	 * @param saleNews
	 * @return String
	 * @throws SQLException 
	 * @throws SerialException 
	 */
	@RequestMapping("/add")
	public void add(SaleNews saleNews,HttpServletRequest request,ModelMap map,
			HttpServletResponse response,@RequestParam(value="affixStr",required=false)String affixStr) throws Exception
	{
		
		PrintWriter out=response.getWriter();
		
		
		String isAffix=request.getParameter("isAffix");

		String[] temps=null;
		saleNews.setBranchId(saleNews.getBranchId()[0].split(","));
		log.info("======================长度"+saleNews.getBranchId()[0]);
		int count=0;
		String json="";
		String newsTitle="";
		String newsContent="";
		String affixPat="";
		String add="";
		String branch="";
		String path = request.getContextPath();
		  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
		if(CommonUtil.isEmpty(saleNews.getNewsTitle().trim()))
		{
			newsTitle="公告标题不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(saleNews.getNewsContent().trim()))
		{
			newsContent="公告内容不能为空！";
			count=count+1;
		}
		else if(saleNews.getNewsTitle().length()<6 || saleNews.getNewsTitle().length()>50)
		{
			newsTitle="公告标题长度必须在6到50位";
			count=count+1;
		}else if(saleNews.getNewsContent().length()>100000)
		{
			newsContent="公告内容长度必须小于100000位";
			count=count+1;
		}else if(!FilterSpesChar.isTrueImage(saleNews.getNewsContent(),basePath))
		{
			newsContent="图片路径不正确，可能会导致图片不能正常显示！";
			count=count+1;
		}
		boolean result=count==0;
		
		if(result)
		{
			saleNews.setCreateDate(new Date());
			saleNews.setUpdateDate(new Date());
			saleNews.setUpdateId(saleNews.getCreateUid());
			saleNews.setViewSeq(0);
			saleNews.setVisitCount(0);
			  
			
			
			boolean flag=newsService.addNews(saleNews);
			if(flag)
			{
				try {
					//保存附件
					affixService.saveAffix(affixStr, "SALENEWS", saleNews.getSaleNewsId());
					add="添加公告成功！";
				} catch (Exception e) {
					add="添加公告失败！";
					log.info("============================添加公告失败原因："+e.getMessage());
				}
				
				map.put("news", saleNews);
			}else 
			{
				add="添加公告失败！";
			}
			}
		
		
		
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");

        
            JSONObject temp = new JSONObject();
            temp.put("result",result);
            temp.put("add", add);
            temp.put("newsTitle",newsTitle);
            temp.put("newsContent",newsContent);
            temp.put("affixPat",affixPat);
            temp.put("branch",branch);
        
        out.print(temp.toString());
		out.flush();
		out.close();
	}
	
	
	/**
	 * 管理公告页面
	 * @param saleNews
	 * @return String
	 */
	@RequestMapping(value="/getnews")
	public String manageNews(@RequestParam(value="currentPage", required=false) String currentPage
			,SaleNews saleNews,HttpServletRequest request,ModelMap map,
			@RequestParam(value="beginCreateDate", required=false)String beginCreateDate,
			@RequestParam(value="endCreateDate", required=false)String endCreateDate)
	{
		
		SaleUsersLogin user=(SaleUsersLogin)request.getSession().getAttribute("user");
		
		int pageIndex;
		try{
			pageIndex = Integer.valueOf(currentPage);
		}catch(Exception ex){
			pageIndex = 1;
		} 
		
		Pagination pagination=null;
		pagination = newsService.searchNews(
				pageIndex,10,request.getContextPath()+"/manage/news/index/getnews?" +
						"&newsTitle="+CommonUtil.jugeAndFixNull(saleNews.getNewsTitle())+
						"&newsContent="+CommonUtil.jugeAndFixNull(saleNews.getNewsContent())+
						"&beginCreateDate="+(CommonUtil.isEmpty(beginCreateDate) ? "" :  beginCreateDate)+
						"&endCreateDate="+(CommonUtil.isEmpty(endCreateDate) ? "" :  endCreateDate)
						,saleNews,beginCreateDate,endCreateDate,user); 
		 
		map.put("pagination", pagination);
		map.put("newsTitle",saleNews.getNewsTitle());
		map.put("newsContent",saleNews.getNewsContent());
		map.put("beginCreateDate", CommonUtil.isEmpty(beginCreateDate) ? ""
				:  beginCreateDate);
		map.put("endCreateDate", CommonUtil.isEmpty(endCreateDate) ? ""
				:  endCreateDate);
		map.put("page",pageIndex); 
 
		return "/manage/news/getnews";
	}
	@RequestMapping("/delete/{saleNewsId}")
	public void delete(HttpServletResponse response,@PathVariable("saleNewsId")String saleNewsId) throws IOException
	{
		response.setContentType("text/json");
		PrintWriter out = response.getWriter();
		boolean flag = newsService.deleteNewsById(saleNewsId);
		JSONObject jo = new JSONObject();
		jo.put("isDel", flag);
		out.print(jo);
		out.flush();
		out.close();
		
		
	}
	
	@RequestMapping(value=("/updatenews/{saleNewsId}"))
	public String updatenews(HttpServletRequest request,
			@PathVariable("saleNewsId")String saleNewsId,
			ModelMap map) throws IOException
	{
		SaleNews news=newsService.getNew(saleNewsId);
		request.setAttribute("new",news);
		
		//附件列表
		List<SaleAffixItem> affixList = affixService.getAffix(
				"SALENEWS", saleNewsId);
		map.put("affixList", affixList);
		request.setAttribute("saleNewsId", saleNewsId);
		return "/manage/news/updatenews";
	}
	
	/**
	 * 编辑公告
	 * @param saleNews
	 * @return String
	 * @throws SQLException 
	 * @throws SerialException 
	 */
	@RequestMapping(value=("/edit"))
	public void update(SaleNews saleNews,HttpServletRequest request,ModelMap map,
			@RequestParam(value = "affixStr", required = false) String affixStr, // 附件列表
			HttpServletResponse response) throws Exception
	{
		String saleNewsId=request.getParameter("saleNewsId");
		System.out.println("=============================="+saleNews.getSaleNewsId());
		//表单验证
		log.info("====================length "+saleNews.getBranchId().length);
		log.info("====================content "+saleNews.getBranchId()[0]);
		String[] temps=null;
		saleNews.setBranchId(saleNews.getBranchId()[0].split(","));
		int count=0;
		String json="";
		String newsTitle="";
		String newsContent="";
		String affixPat="";
		String add="";
		String branch="";
		String path = request.getContextPath();
		  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
		if(CommonUtil.isEmpty(saleNews.getNewsTitle().trim()))
		{
			newsTitle="公告标题不能为空！";
			count=count+1;
		}else if(CommonUtil.isEmpty(saleNews.getNewsContent().trim()))
		{
			newsContent="公告内容不能为空！";
			count=count+1;
		}
		else if(saleNews.getNewsTitle().length()<6 || saleNews.getNewsTitle().length()>50)
		{
			newsTitle="公告标题长度必须在6到50位";
			count=count+1;
		}else if(saleNews.getNewsContent().length()>100000)
		{
			newsContent="公告内容长度必须小于100000位";
			count=count+1;
		}else if(!FilterSpesChar.isTrueImage(saleNews.getNewsContent(),basePath))
		{
			newsContent="图片路径不正确，可能会导致图片不能正常显示！";
			count=count+1;
		}
		boolean result=count==0;
		
		response.setContentType("text/html");

		PrintWriter out = response.getWriter();

		SaleUsersLogin user = (SaleUsersLogin) request.getSession()
				.getAttribute("user");

		
		
		if(result)
		{
			saleNews.setSaleNewsId(saleNewsId);
			saleNews.setCreateDate(new Date());
			saleNews.setUpdateDate(new Date());
			saleNews.setUpdateId(user.getSaleUsersLoginId());
			saleNews.setViewSeq(0);
			boolean flag=newsService.updateNews(saleNews);
			if(flag)
			{
				try {
					//保存附件
					affixService.saveAffix(affixStr, "SALENEWS", saleNewsId);
					add="编辑公告成功！";
				} catch (Exception e) {
					add="编辑公告失败！";
				}
			}else 
			{
				add="编辑公告失败！";
			}
			
		}
		
		response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        request.setCharacterEncoding("UTF-8");

        
            JSONObject temp = new JSONObject();
            temp.put("result",result);
            temp.put("add", add);
            temp.put("newsTitle",newsTitle);
            temp.put("newsContent",newsContent);
            temp.put("affixPat",affixPat);
            temp.put("branch",branch);
        
        out.print(temp.toString());
		out.flush();
		out.close();
	}
	
	/**
	 * 查看公告
	 * @param saleNews
	 * @return String
	 * @throws SQLException 
	 * @throws SerialException 
	 */
	@RequestMapping(value=("/view"))
	public String view(HttpServletRequest request,ModelMap map,
			HttpServletResponse response) throws Exception
	{
		String saleNewsId=request.getParameter("saleNewsId");
		SaleNews saleNews=newsService.getNew(saleNewsId);
		saleNews.setNewsContent(saleNews.getNewsContent().replace("&amp;lt;", "&lt;").replace("&amp;gt;", "&gt;"));
		map.put("new", saleNews);
		//附件列表
		List<SaleAffixItem> affixList = affixService.getAffix(
				"SALENEWS", saleNewsId);
		map.put("affixList", affixList);
		return "/manage/news/view";
	}
}
